﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Services.Description;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Xsl;

public partial class find : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void On_Inserting_Friend(Object sender, SqlDataSourceCommandEventArgs e)
    {
        SqlParameter sp = new SqlParameter("currentUser", User.Identity.Name);
        sp.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp);

        SqlParameter sp2 = new SqlParameter("friend", FriendInput.Text);
        sp2.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp2);

        Results.Text = "<p> You have friended " + FriendInput.Text + "! </p>";
    }

    protected void On_Inserting_Feed(Object sender, SqlDataSourceCommandEventArgs e)
    {
        SqlParameter sp = new SqlParameter("currentUser", User.Identity.Name);
        sp.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp);

        SqlParameter sp2 = new SqlParameter("url", FeedInput.Text);
        sp2.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp2);

        Results.Text = "<p> You have added feed " + FeedInput.Text + "! </p>";
    }

    protected void On_Inserting_Feed_Title(Object sender, SqlDataSourceCommandEventArgs e)
    {
        SqlParameter sp = new SqlParameter("url", FeedInput.Text);
        sp.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp);


        XmlReader reader = XmlReader.Create(FeedInput.Text);
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        XmlElement root = doc.DocumentElement;
        XmlNodeList node = root.GetElementsByTagName("title");
        string rssTitle = (node.Item(0).InnerXml);


        SqlParameter sp2 = new SqlParameter("title", rssTitle);
        sp2.Direction = ParameterDirection.Input;
        e.Command.Parameters.Add(sp2);

    }

    private void PerformSearch()
    {
        const string apikey = "7CABFECE94DA7F87B8FA525A341A7219"; // Your AppID here 
        const string userId = "p3davis@hotmail.com";

        // Construct the Search and Search URL 
        StringBuilder requestUrl = new StringBuilder();
        string query = Server.UrlEncode(searchText.Text);
        requestUrl.Append("http://www.bloglines.com/search?format=publicapi&apiuser="); //+ userId + "&apikey=" + apikey + "&q=" + query + "&t=f&ql=en&s=f&pop=l&news=m";
        requestUrl.Append(userId);
        requestUrl.Append("&apikey=");
        requestUrl.Append(apikey);
        requestUrl.Append("&q=");
        requestUrl.Append(query);
        requestUrl.Append("&t=f&ql=en&s=f&pop=l&news=m");


        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl.ToString()) as HttpWebRequest;
            request.ContentType = "text/xml;charset=\"utf-8\"";
            request.Accept = "text/xml";
            request.Method = "GET";
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                {
                    //String temp = streamReader.ReadToEnd();

                    XmlReader reader = XmlReader.Create(streamReader);

                    XslCompiledTransform transform = new XslCompiledTransform();
                    StringBuilder output = new StringBuilder();
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.ConformanceLevel = ConformanceLevel.Auto;
                    XmlWriter write = XmlWriter.Create(output, settings);
                    transform.Load(Server.MapPath("transforms/searchresults.xsl"));

                    transform.Transform(reader, write);

                    Results.Text = output.ToString();
                }

            }
        }
        catch (Exception ex)
        {

        }


    }


//Button Clicks

    public void AddFriend_Click(Object sender, EventArgs E)
    {
        if (FriendInput.Text == "")
        {
            lblAddFriend.Text = "Please enter a valid arf user name";
        }
        else
        {
            SqlDataSource3.SelectParameters.Clear();
            SqlDataSource3.SelectParameters.Add(new Parameter("AddedName", TypeCode.String, FriendInput.Text));            
            DataSourceSelectArguments dssa = new DataSourceSelectArguments();            
            dssa.MaximumRows = 10;
            dssa.AddSupportedCapabilities(DataSourceCapabilities.Page);
            DataView dv = (DataView)SqlDataSource3.Select(dssa);

            if (dv.Count > 0)
            {
                SqlDataSource4.SelectParameters.Clear();
                SqlDataSource4.SelectParameters.Add(new Parameter("CurrUser", TypeCode.String, User.Identity.Name));
                SqlDataSource4.SelectParameters.Add(new Parameter("AddedName", TypeCode.String, FriendInput.Text));
                DataView dv2 = (DataView)SqlDataSource4.Select(dssa);
                if (dv2.Count == 0)
                {
                    if (FriendInput.Text == dv[0].Row[0].ToString().Trim())
                    {
                        lblAddFriend.Visible = false;
                        if (Page.IsValid == true)
                        {
                            SqlDataSource1.Insert();
                        }
                    }
                }
                else
                {
                    lblAddFriend.Text = "You are already friends with this person";
                }
            }
            else
            {
                lblAddFriend.Text = "Please enter a valid arf user name";
            }
        }
    }

    protected void AddFeed_Click(object sender, EventArgs e)
    {
        if (FeedInput.Text == "")
        {
            lblAddFeed.Text = "Please enter a valid feed";
        }
        else
        {
            if (urlRegExValidator(FeedInput.Text))
            {
                SqlDataSource5.SelectParameters.Clear();
                SqlDataSource5.SelectParameters.Add(new Parameter("CurrUser", TypeCode.String, User.Identity.Name));
                SqlDataSource5.SelectParameters.Add(new Parameter("AddedURL", TypeCode.String, FeedInput.Text));
                DataSourceSelectArguments dssa = new DataSourceSelectArguments();
                dssa.MaximumRows = 10;
                dssa.AddSupportedCapabilities(DataSourceCapabilities.Page);
                DataView dv = (DataView)SqlDataSource5.Select(dssa);
                if (dv.Count == 0)
                {
                    lblAddFeed.Visible = false;
                    if (Page.IsValid == true)
                    {
                        SqlDataSource2.Insert();
                        SqlDataSource6.Insert();
                    }
                }
                else
                {
                    lblAddFeed.Text = "You are already subscribed to that feed";
                }
            }
            else
            {
                lblAddFeed.Text = "Please enter a valid feed";
            }
        }
    }

    private bool urlRegExValidator(string url)
    {
        string strRegex = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@ 
        + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184 
        + "|" // allows either IP or domain 
        + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www. 
        + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain 
        + "[a-z]{2,6})" // first level domain- .com or .museum 
        + "(:[0-9]{1,4})?" // port number- :80 
        + "((/?)|" // a slash isn't required if there is no file name 
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        Regex re = new Regex(strRegex);

        return re.IsMatch(url);

    }

    protected void Search_Click(object sender, EventArgs e)
    {
        if (searchText.Text == "")
        {
            lblSearchFeeds.Text = "Please enter a valid search query";
        }
        else
        {
            lblSearchFeeds.Visible = false;
            if (Page.IsValid == true)
            {
                PerformSearch();
            }
        }

    }

    protected void PlaceHolder1_Load(object sender, EventArgs e)
    {
        LinkButton lb = new LinkButton();
        lb.CommandName = "UpdatePaper";
        lb.Text = "Update";
        lb.ID = "Update";
        lb.Command += new System.Web.UI.WebControls.CommandEventHandler(showFriendFeed_Click);
        lb.Controls.Add(lb);
    }

    protected void showFriendFeed_Click(object sender, EventArgs e)
    {
    }
}